# -*- encoding: utf-8 -*-
"""
file       : receive_http.py
Date       : 2025/01/09 19:30:30
Author     : Kerry
version    : Rev 0.1
Des:       : 
"""


import base64

import cv2
import numpy as np
from flask import Flask, json, jsonify, request
from flask_cors import *


# 端口号
port = 16000

# URL : /update-model-result"

# app
app = Flask(__name__)

# 跨域支持
CORS(app, supports_credentials=True)


@app.after_request
def after(resp):
    resp.headers["Access-Control-Allow-Origin"] = "*"
    resp.headers["Access-Control-Allow-Methods"] = "GET,POST"
    resp.headers["Access-Control-Allow-Headers"] = "*"
    return resp


@app.route("/")
def home():
    return "hello"


@app.route("/update-model-result", methods=["POST"])
def rtsp_result():

    global g_rtsp_data

    # 获取请求中的 JSON 数据
    data = request.get_json()

    if data:

        result_img = data.pop("result_img", None)

        if result_img is not None:
            if len(result_img) > 0:

                # # 解码Base64字符串
                image_data = base64.b64decode(result_img)

                # # 转换为NumPy数组
                image_array = np.frombuffer(image_data, dtype=np.uint8)

                # # 解码为图像
                image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)

                # # 保存图片
                cv2.imwrite("rtsp_result.jpg", image)

        # 将 JSON 数据保存到文件中
        with open("rtsp_result.json", "w") as json_file:
            json.dump(data, json_file, indent=4)

    return jsonify({"message": "", "data": {}, "code": 200})


if __name__ == "__main__":

    app.run(host="0.0.0.0", port=port, debug=True)
